import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import KK_IPC_PROTOCOLS from '../ipc/protocol'
import { LogMessage } from '../LogService/LogType'

// Custom APIs for renderer
const api = {}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}

contextBridge.exposeInMainWorld('electronAPI', {
  runScript: (script) => ipcRenderer.invoke('run-script', script),
  executeScript: (script: string) => ipcRenderer.invoke(KK_IPC_PROTOCOLS.SCRIPT_EXECUTE, script),
  startLogCollection: (log?: LogMessage) => ipcRenderer.invoke("startLogCollection", log),
  stopLogCollection: () => ipcRenderer.invoke("stopLogCollection"),
  logToWorker: (logData: LogMessage) =>ipcRenderer.send("log-message", logData),
  minimize: () => ipcRenderer.send('window-minimize'),
  maximize: () => ipcRenderer.send('window-maximize'),
  close: () => ipcRenderer.send('window-close')
})

import { ConnectRequest, ConnectResponse } from '../opcua/types'
import { DataValue } from 'node-opcua'

contextBridge.exposeInMainWorld('opcua', {
  connect: (args: ConnectRequest): Promise<ConnectResponse> =>
    ipcRenderer.invoke('opcua-connect', args),
  onOpcuaDataChanged: (callback: (value: DataValue) => void) => {
    ipcRenderer.on('opcua-data-changed', (_, value) => callback(value))
  },
  onDataChanged: (callback: (value: DataValue) => void) => {
    ipcRenderer.on('data-changed', (_, value) => callback(value))
  }
})
